﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.Text.RegularExpressions;
using ICSharpCode.SharpZipLib.GZip;
using System.Text;

namespace TanzimSaqib.NewsFramework
{
    public static class WebUtil
    {

        public static void GetResponseText(string url, Action<string> action)
        {
            var request = WebRequest.CreateHttp(url);

            request.BeginGetResponse(ar =>
            {
                string responseText;
                using (var response = request.EndGetResponse(ar))
                    responseText = response.GetResponseText();
                Deployment.Current.Dispatcher.BeginInvoke(() => action(responseText));
            }, null);
        }

        public static string GetResponseText(this WebResponse response)
        {
            using (Stream stream = response.IsCompressed()
                                       ? new GZipInputStream(response.GetResponseStream())
                                       : response.GetResponseStream())
            {
                return new StreamReader(stream, Encoding.GetEncoding("utf-8")).ReadToEnd();
            }
        }

        public static bool IsCompressed(this WebResponse response)
        {
            return Regex.IsMatch((response.Headers["Content-Encoding"] ?? "")
                                     .ToLower(), "(gzip|deflate)");
        }


    }

}
